package com.moss.framework.config;

import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.moss.common.exception.ServiceException;
import com.moss.common.exception.URIPermissionException;
import com.moss.common.jwt.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class JWTInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(HandlerInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取请求头中的token令牌
        log.info("请求路径--[{}],请求参数-[{}]",request.getRequestURL(), JSONObject.toJSONString(request.getParameterMap()));
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            throw new URIPermissionException("令牌为空");
        }
        try {
            JwtUtil.verify(token);//验证令牌
            return true;//放行请求
        } catch (SignatureVerificationException e) {
            throw new URIPermissionException("token异常-无效签名");
        } catch (TokenExpiredException e) {
            throw new URIPermissionException("token异常-token过期,请重新获取");
        } catch (AlgorithmMismatchException e) {
            //token算法不一致!
            throw new URIPermissionException("token异常-算法异常");
        } catch (Exception e) {
            throw new URIPermissionException("token异常-无效token");
        }
    }
}
